<!-- PlanDetail.vue -->
<template>
    <div class="plan-detail">
      <!-- 基础信息 -->
      <div class="base-info">
        <van-cell-group class="info-card">
          <div class="plan-header">
            <span class="plan-name">{{ plan.name }}</span>
            <van-tag :type="getPlanStatusType()">{{ getPlanStatusText() }}</van-tag>
          </div>
          <div v-if="plan.description" class="plan-desc">{{ plan.description }}</div>
          <div class="cycle-info">
            <van-icon name="clock-o" />
            <span>{{ getCycleText() }}</span>
          </div>
        </van-cell-group>
      </div>
  
      <!-- 周期选择 -->
      <div class="cycle-select">
        <div class="cycle-range">{{ formatDateRange(getCurrentCycle()?.startTime, getCurrentCycle()?.endTime) }}</div>
        <div class="cycle-buttons">
          <span
              v-if="latestCycle"
              class="cycle-button"
              :class="{ active: activeCycle === 'latest' }"
              @click="() => selectCycle('latest')"
          >
            最新周期
          </span>
          <span
              v-if="prevCycle"
              class="cycle-button"
              :class="{ active: activeCycle === 'prev' }"
              @click="() => selectCycle('prev')"
          >
            上一周期
          </span>
          <span
              v-if="historyCycles.length > 0"
              class="cycle-button"
              :class="{ active: activeCycle === 'history' }"
              @click="showHistoryPicker"
          >
            历史周期
          </span>
        </div>
  
        <!-- 历史周期选择弹窗 -->
        <van-popup
            v-model:show="showHistoryPopup"
            position="bottom"
            round
        >
          <van-picker
              :columns="historyCycleColumns"
              @confirm="onHistoryCycleSelect"
              @cancel="closeHistoryPicker"
              show-toolbar
              title="选择历史周期"
          />
        </van-popup>
      </div>
  
      <!-- 任务状态筛选 -->
      <div class="status-filter">
        <van-tabs v-model:active="activeStatus" @change="handleStatusChange" sticky swipeable>
          <van-tab name="ALL" title="全部" />
          <van-tab name="PENDING" title="待完成" />
          <van-tab name="COMPLETED" title="已完成" />
          <van-tab name="OVERDUE_PENDING" title="超期未完成" />
          <van-tab name="OVERDUE_COMPLETED" title="超期完成" />
        </van-tabs>
      </div>
  
      <!-- 点位列表 -->
      <div class="point-list">
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
          <van-list
              v-model:loading="loading"
              :finished="finished"
              :error="error"
              error-text="请求失败，点击重试"
              @load="onLoad"
          >
            <div v-if="pointRecords.length > 0">
              <van-cell-group
                  v-for="record in filteredRecords"
                  :key="record.id"
                  class="point-item"
              >
                <van-cell>
                  <template #title>
                    <div class="point-header">
                      <span class="point-name">{{ record.name }}</span>
                      <van-tag :type="getStatusType(record.status)">
                        {{ getStatusText(record.status) }}
                      </van-tag>
                    </div>
                  </template>
                  <template #label>
                    <div class="point-info">
                      <div class="point-group">{{ record.groupPath }}</div>
                      <div class="point-forms" v-if="record.formIds?.length">
                        关联表单：{{ record.formIds.length }}个
                      </div>
                      <div class="check-info" v-if="record.inspectorName">
                        <span>检查人：{{ record.inspectorName }}</span>
                        <span>时间：{{ formatTime(record.reportTime) }}</span>
                      </div>
                    </div>
                  </template>
                </van-cell>
              </van-cell-group>
            </div>
  
            <!-- 空状态 -->
            <Empty v-if="!filteredRecords.length" description="暂无记录" />
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
  </template>
  
  <script setup>
  import {computed, onMounted, ref, inject} from 'vue'
  import {useRoute} from 'vue-router'
  import { getCycles, getPlanDetail, getPoints } from "@/api/common"
  import { Empty, Tag as VanTag, Picker as VanPicker } from "vant"
  
  const route = useRoute()
  const toast = inject("toast")
  const planId = route.query.id
  
  // 状态管理
  const loading = ref(false)
  const refreshing = ref(false)
  const error = ref(false)
  const finished = ref(false)
  const showHistoryPopup = ref(false)
  
  // 数据
  const plan = ref({})
  const cycles = ref([])
  const pointRecords = ref([])
  const activeCycle = ref('latest')
  const activeStatus = ref('ALL')
  const selectedHistoryCycle = ref(null)
  
  // 计算属性
  const latestCycle = computed(() => cycles.value[0])
  const prevCycle = computed(() => cycles.value[1])
  const historyCycles = computed(() => cycles.value.slice(2))
  
  const historyCycleColumns = computed(() => {
    return historyCycles.value.map(cycle => ({
      text: formatDateRange(cycle.startTime, cycle.endTime),
      value: cycle.startTime
    }))
  })
  
  const filteredRecords = computed(() => {
    if (activeStatus.value === 'ALL') return pointRecords.value
    return pointRecords.value.filter(record => record.status === activeStatus.value)
  })

  // 周期相关方法
  const getCurrentCycle = () => {
    switch (activeCycle.value) {
      case 'latest':
        return latestCycle.value
      case 'prev':
        return prevCycle.value
      case 'history':
        return selectedHistoryCycle.value
      default:
        return latestCycle.value
    }
  }
  
  const selectCycle = (cycleType) => {
    activeCycle.value = cycleType
    if (cycleType !== 'history') {
      selectedHistoryCycle.value = null
    }
    handleCycleChange()
  }
  
  const showHistoryPicker = () => {
    showHistoryPopup.value = true
  }
  
  const closeHistoryPicker = () => {
    showHistoryPopup.value = false
    if (!selectedHistoryCycle.value) {
      activeCycle.value = 'latest'
    }
  }
  
  const onHistoryCycleSelect = (selectedOptions) => {
    const selectedStartTime = selectedOptions.value
    selectedHistoryCycle.value = historyCycles.value.find(
        cycle => cycle.startTime === selectedStartTime
    )
    activeCycle.value = 'history'
    showHistoryPopup.value = false
    handleCycleChange()
  }
  
  const handleCycleChange = () => {
    pointRecords.value = []
    finished.value = false
    loading.value = true
    fetchPointRecords()
  }
  
  // 通用事件处理
  const handleStatusChange = () => {
    // 仅更新视图筛选，无需重新请求数据
  }
  
  const onRefresh = () => {
    finished.value = false
    error.value = false
    fetchPointRecords()
  }
  
  const onLoad = () => {
    finished.value = true
  }
  
  // 工具方法
  const formatDateRange = (start, end) => {
    if (!start || !end) return ''
    const formatDate = (date) => {
      const d = new Date(date)
      return `${d.getMonth() + 1}月${d.getDate()}日`
    }
    return `${formatDate(start)} - ${formatDate(end)}`
  }
  
  const formatTime = (time) => {
    if (!time) return ''
    const date = new Date(time)
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  const getCycleText = () => {
    if (!plan.value.cycleType) return ''
    const type = plan.value.cycleType === 'DAILY' ? '天' : '周'
    return `每${plan.value.intervalCount}${type}`
  }
  
  const getStatusType = (status) => {
    const types = {
      'PENDING': 'warning',
      'COMPLETED': 'success',
      'OVERDUE_PENDING': 'danger',
      'OVERDUE_COMPLETED': 'primary'
    }
    return types[status] || 'default'
  }
  
  const getStatusText = (status) => {
    const texts = {
      'PENDING': '待完成',
      'COMPLETED': '已完成',
      'OVERDUE_PENDING': '超期未完成',
      'OVERDUE_COMPLETED': '超期完成'
    }
    return texts[status] || '未知状态'
  }
  
  const getPlanStatusType = () => {
    const stats = computePlanStats()
    if (stats.overduePending > 0) return 'danger'
    if (stats.pending > 0) return 'warning'
    if (stats.overdueCompleted > 0) return 'primary'
    return 'success'
  }
  
  const getPlanStatusText = () => {
    const stats = computePlanStats()
    if (stats.overduePending > 0) return `超期未完成 ${stats.overduePending}`
    if (stats.pending > 0) return `待完成 ${stats.pending}`
    if (stats.pending === 0 && stats.overduePending === 0) return '全部完成'
    return '已完成'
  }
  
  const computePlanStats = () => {
    return pointRecords.value.reduce((acc, record) => {
      switch (record.status) {
        case 'PENDING':
          acc.pending++
          break
        case 'COMPLETED':
          acc.completed++
          break
        case 'OVERDUE_PENDING':
          acc.overduePending++
          break
        case 'OVERDUE_COMPLETED':
          acc.overdueCompleted++
          break
      }
      return acc
    }, {
      pending: 0,
      completed: 0,
      overduePending: 0,
      overdueCompleted: 0
    })
  }

  const fetchPlanDetail = async () => {
    try {
      plan.value = await getPlanDetail(planId)
    } catch (error) {
      toast.error(error.message)
    }
  }
  const fetchCycles = async () => {
    try {
      cycles.value = await getCycles(planId)
    } catch (error) {
      toast.error(error.message)
    }
  }
  function fetchPointRecords() {
    const currentCycle = getCurrentCycle()
    if (!currentCycle) return
    loading.value = true
    getPoints(planId, currentCycle.startTime).then(res => {
      pointRecords.value = res
      error.value = false
      loading.value = false
      refreshing.value = false
      finished.value = true
    }, err => {
      error.value = false
      toast.msg(err.message)
      loading.value = false
      refreshing.value = false
      finished.value = true
    })
  }

  // 页面初始化
  onMounted(async () => {
    await Promise.all([
      fetchPlanDetail(),
      fetchCycles()
    ])
    fetchPointRecords()
  })
  </script>
  
  <style scoped>
  .plan-detail {
    min-height: 100vh;
    background-color: #f7f8fa;
  }
  
  .base-info {
    padding: 12px;
  }
  
  .info-card {
    background: #fff;
    border-radius: 8px;
    padding: 16px;
  }
  
  .plan-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }
  
  .plan-name {
    font-size: 18px;
    font-weight: 500;
  }
  
  .plan-desc {
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
    line-height: 1.5;
  }
  
  .cycle-info {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #666;
    font-size: 14px;
  }
  
  .cycle-select {
    background: #fff;
    margin-bottom: 12px;
    padding: 16px;
  }
  
  .cycle-range {
    font-size: 16px;
    font-weight: 600;
    color: #323233;
    margin-bottom: 12px;
  }
  
  .cycle-buttons {
    display: flex;
    gap: 24px;
  }
  
  .cycle-button {
    font-size: 14px;
    color: #666;
    cursor: pointer;
    position: relative;
    padding: 4px 0;
  }
  
  .cycle-button.active {
    color: #1989fa;
    font-weight: 500;
  }
  
  .cycle-button.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #1989fa;
    border-radius: 1px;
  }
  
  .point-list {
    padding: 12px;
  }
  
  .point-item {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 12px;
  }
  
  .point-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .point-name {
    font-size: 16px;
    font-weight: 500;
  }
  
  .point-info {
    font-size: 14px;
    color: #666;
  }
  
  .point-group {
    margin-bottom: 4px;
  }
  
  .point-forms {
    margin-bottom: 4px;
  }
  
  .check-info {
    display: flex;
    justify-content: space-between;
  }
  
  :deep(.van-cell) {
    padding: 16px;
    line-height: 1.5;
  }
  
  :deep(.van-tabs__line) {
    background-color: #1989fa;
  }
  
  :deep(.van-tab--active) {
    color: #1989fa;
  }
  
  :deep(.van-picker-column) {
    font-size: 14px;
  }
  
  :deep(.van-tag) {
    padding: 4px 8px;
  }
  </style>